<!DOCTYPE html>
<html>
<head>
    <title>鹿鹿泽健身会员体测</title>
    <link rel="stylesheet" href="../static/css/minghu.css">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="icon" href="{{ url_for('static', filename='favicon.ico') }}" type="image/x-icon">
</head>
<body>
    {% include 'show_ins_info.html' %}
    <div id="allPlanContents">
        <h1>会员体测结果及训练计划</h1>
        <hr>
        <h4>会员姓名<span style="width:25px;"></span> <input id="cusName" style="width: 100px;" oninput="handleInput()"></h4>
        <div id="insSelBox"><h4>教&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;练&nbsp;<span style="width:25px;"></span> <select id="insSelect"></select></h4></div>
        <div id="cusList" class="cus-list-result" style="display: none;top:154px;left:196px;"></div>
        <div id="bodyHistory" class="body-history-list"></div>
        <hr>
        <div><h2>录入本次体测数据</h2></div>
        <div class="form-row" ><h4 style="width:80px;">体测日期</h4><input id='date' type='date' ></div>
        <div id="bodyMsrData" >
            <div class="form-row" ><h4 style="width:80px;">身高</h4> <input id='ht' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">体重</h4> <input id='wt' type="number" min="0" style="width:90px;margin-right:10px;"> Kg</div>
            <div class="form-row" ><h4 style="width:80px;">胸围 </h4> <input id='chest' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">左臂围 </h4> <input id='l_arm' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">右臂围</h4>  <input id='r_arm' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">腰围</h4>  <input id='waist' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">臀围</h4>  <input id='hip' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">左大腿围</h4>  <input id='l_leg' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">右大腿围</h4>  <input id='r_leg' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">左小腿围</h4>  <input id='l_calf' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
            <div class="form-row" ><h4 style="width:80px;">右小腿围</h4>  <input id='r_calf' type="number" min="0" style="width:90px;margin-right:10px;"> cm</div>
        </div>  
        <hr>
        <div id="insEvaluate" >
            <div class="form-row" ><h4 style="width:80px;">心肺 </h4><input id='heart' type="number" min="0" max="10" style="width:90px;margin-right:10px;"> 分（满分10分）</div>
            <div class="form-row" ><h4 style="width:80px;">平衡</h4> <input id='balance' type="number" min="0" max="10" style="width:90px;margin-right:10px;"> 分（满分10分）</div>
            <div class="form-row" ><h4 style="width:80px;">力量</h4> <input id='power' type="number" min="0" max="10" style="width:90px;margin-right:10px;"> 分（满分10分）</div>
            <div class="form-row" ><h4 style="width:80px;">柔韧性 </h4><input id='flex' type="number" min="0" max="10" style="width:90px;margin-right:10px;"> 分（满分10分）</div>
            <div class="form-row" ><h4 style="width:80px;">核心 </h4><input id='core' type="number" min="0" max="10" style="width:90px;margin-right:10px;"> 分（满分10分）</div>
        </div>
        <hr>
        <h2>训练计划</h2>
        <div>
            <h3 id="bodyProblemsTitle">体测发现问题</h3>
            <textarea id="bodyProblems" class='train-plan-inputbox' style="margin-left:10px;"></textarea>
        </div>
        
        <div>
            <h3>会员健身需求</h3>
            <textarea id="cusGoal" class='train-plan-inputbox' style="margin-left:10px;" ></textarea>
        </div>
       
        <div>
            <h3>教练针对性建议</h3>
            <textarea id="insSuggest" class='train-plan-inputbox' style="margin-left:10px;" ></textarea>
        </div>
        <div id="trainSummaryBox" class="form-row">
            <div>
                <h3>上一阶段训练回顾</h3>
                <textarea id="trainSummary" style="width:200px;height:80px;margin-left:10px;" ></textarea>
            </div>
        </div>
        <hr>
        <div id="stageBox">
            <h3>下一阶段训练计划</h3>
            <div class="form-row">
                <h5>会员所处阶段 </h5>
                <select id="stageSelect">
                </select>
            </div>
            <div class="form-row">
                <h5>阶段目标</h5><textarea id="stageGoal" class='train-plan-inputbox' ></textarea>
            </div>

            <div id="trainDetail-0" style="background-color: rgb(241, 245, 252);">
                <div><h3 id="trainRecCount-0" class="train-reccount" style="background-color: rgb(63, 91, 161);">阶段训练计划分解  第1条</h3></div>
                <div id="purpose-0" class="form-row">
                    <h5>训练目标</h5>
                    <textarea id="purposeTxt-0" class='train-plan-inputbox'></textarea>
                </div>
                <div id="part-0" class="form-row">
                    <h5>部位分化</h5>
                    <textarea id="partTxt-0" class='train-plan-inputbox'></textarea>
                </div>
                <div id="frqcy-0" class="form-row">
                    <h5 style="margin-top:10px;margin-bottom:10px;">训练频率<br>(天/周)</h5>
                    <input id="frqcyTxt-0" style="width:100px;">
                </div>
                <div id="strength-0" class="form-row">
                    <h5>训练强度</h5>
                    <input id="strengthTxt-0" style="width:100px;">
                </div>
                <div id="benifit-0" class="form-row">
                    <h5>预期训练收益</h5>
                    <textarea id="benifitTxt-0" class='train-plan-inputbox'></textarea>
                </div>
                <div id="type-0" class="form-row">
                    <h5 style="margin-top:10px;margin-bottom:10px;">训练类型</h5>
                    <select id="typeTxt-0" ></select>
                </div>
                <div id="prd-0" class="form-row">
                    <h5 style="margin-top:10px;margin-bottom:10px;">训练用时<br>（分钟）</h5>
                    <input id="prdTxt-0" style="width:100px;">
                </div>
                <div id="active-0" class="form-row">
                    <h5 style="margin-top:10px;margin-bottom:10px;">激活拉伸时间<br>（分钟）</h5>
                    <input id="activeTxt-0" style="width:100px;">
                </div>
                <hr>
                
            </div>
           
        </div>
        <button id="copyDetail" onclick="copyDetail();">添加一条阶段训练计划</button>
   
        <hr>
        
        <div id="compPicBox">
            <h3>上传对比图</h3>
            <input type="file" name='image' id="fileInput" accept="image/*" style="display: none;">
            <div id="uploadMsg" ></div>
            <button id='browseButton' onclick="openFileBrowser();" style="margin-top:20px;">浏览</button>
            <button id="upload" onclick="uploadFile();">上传</button>
        </div>

        <div id="processingModel" style="display: none;">
            <!-- 这里是弹出框的内容 -->
            <p style="color:rgb(40, 57, 78);font-size:30px;">正在处理中，请稍候...</p>
        </div>
        <hr>
        <div>
            <button id="tempSaveButton" onclick="tempSave()" style="margin-top:40px;">暂存</button>
            <button id="editButton" onclick="enableEdit()">返回修改</button>
            <button id="submit" onclick="submit()" style="margin-top:40px;">提交</button>
        </div>
        
    </div>


    <script src="../static/js/common.js"></script>
    <script>
        let cus_list;
        let ins_list;
        let train_list;
        let copyCountBody=0;
        let blockOrderBody=1;
        let deleteCountBody=0;
        let insName;
        let insId;
        let insRole;
        let insIdReload;
        let selectedFile;
        let trainTypes;

        document.addEventListener("DOMContentLoaded",function(){
            // loginCheck();
            const insInfo=hideInsSelectBlockAndGetInsInfo();
            insName=insInfo['sessionInsName'];
            insId=insInfo['sessionInsId'];
            insRole=insInfo['sessionInsRole'];

            const insSelBox=document.getElementById('insSelBox');
            if(insRole==='ins'){
                insSelBox.style.display='none';
            }else{
                insSelBox.style.display='block';
            }
            
            selectToday(id='date',format='date');

            fetch('/get_template_info', {
                method: 'POST',
                headers: {
                    'Content-Type': 'text/plain'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log(data);

                  })
                .catch(error => console.error('Error:', error));

            fetch('/get_cus_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                    }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                // console.log(data);
                cus_list=data;
                  })
                .catch(error => console.error('Error:', error));


            fetch('/get_ins_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log('ins list:',data);
                generateInsSel(data['ins_list']);

                 })
                .catch(error => console.error('Error:', error));

            fetch('/get_input_body_page_options', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
                    const stages=data['res_stage'];
                    const types=data['res_type'];
                    trainTypes=data['res_type'];
                    
                    const stageSelect=document.getElementById('stageSelect');
                    stages.forEach(stage=>{
                        const opt=document.createElement('option');
                        opt.value=stage;
                        opt.textContent=stage;
                        stageSelect.appendChild(opt)
                    });

                    const typeSelect=document.getElementById('typeTxt-0');
                    types.forEach(tp=>{
                        const opt=document.createElement('option');
                        opt.value=tp;
                        opt.textContent=tp;
                        typeSelect.appendChild(opt)
                    });

                 })
                .catch(error => console.error('Error:', error));

                

                fetch('/get_train_list', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
                })
                .then(response => response.json())
                .then(data => {
            //将data赋值给块变量cus_list，供后面的handleInput使用
                console.log(data);
                train_list=data;

                 })
                .catch(error => console.error('Error:', error));

                const inputs=document.querySelectorAll('input');
                document.getElementById("submit").style.display = "none";
                document.getElementById("editButton").style.display = "none";
                document.getElementById("tempSaveButton").disabled = true;
                document.getElementById("browseButton").disabled = true;
                document.getElementById("upload").disabled = true;
                document.getElementById('uploadMsg').textContent='';
                // document.getElementById("trainSummary").disabled = true;

                fillDetailPrompt(0);
                checkTrainSummaryShow();


                document.getElementById('fileInput').addEventListener('change', handleFileSelection);
                const fileInput = document.getElementById("fileInput");
                fileInput.addEventListener("change", handleFileSelection);
                
        });

        function checkTrainSummaryShow(){
            const trainSummary=document.getElementById('trainSummary');
            const cusName=document.getElementById('cusName').value.trim();
            const planDate=dateToString(document.getElementById('date').value,'date');
            const data={
                'cus_name':cusName,
                'plan_date':planDate
            }
            fetch('/get_plan_history', {
                    method:"POST",
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body: JSON.stringify(data)
                })
                .then(response => response.json())
                .then(data => {           
                    // console.log(data['res'])
                    if(data['res']==='ok'){
                        // trainSummary.disabled=false;

                    }else{
                        //第一次录入时，没有既往记录，故回顾不用写，为空。
                        // trainSummary.disabled=true;
                        trainSummary.value='';
                    }
                })
                .catch(error => console.error('Error:', error));
        }

        function generateInsSel(dat){
            const insSel=document.getElementById('insSelect');
            if(insRole==='ins'){
                insSelBox.style.display='none';
            }else{
                insSelBox.style.display='block';            
                dat.forEach(item=>{
                    const opt=document.createElement('option');
                    opt.value=item.slice(0,8);
                    opt.textContent=item.slice(8,);
                    insSel.appendChild(opt);
                });
            }
        }

        function reFillTempSave(dataString){
            // console.log(selectedFile)
            if(!selectedFile){
                window.selectedFile=0;
            }
            const data=JSON.parse(dataString);
            let insIdPage;
            if(insRole==='admin'){
                insIdPage=document.getElementById('insSelect').value;
            }else if(insRole==='ins'){
                insIdPage=data['train_items']['ins_id'];
            }else{
                insIdPage=data['train_items']['ins_id'];
            }
            
           
            // console.log(data);
            document.getElementById('cusName').value=data['train_items']['cus_name'];
            const cusName=data['train_items']['cus_name'];
            copyCountBody=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-copyCountBody'));
            deleteCountBody=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-deleteCountBody'));
            blockOrderBody=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-blockOrderBody'));
            // selectedFile=parseInt(localStorage.getItem(insIdPage+'-'+cusName+'-selectedFileBody'));

            if(blockOrderBody>=2){
                const deleteButton=document.getElementById('deleteTrain-'+(blockOrderBody-1));
                deleteButton.addEventListener('click',function(){
                    deleteTrainBlock(this,'y');
                });
            }

            
            if(insRole==='admin'){
                document.getElementById('insSelect').value=data['train_items']['ins_id'];               

            }
            //读取暂存的insid
            insIdReload=data['train_items']['ins_id']; 

            // 回写之前的选项
            document.getElementById('cusName').value=data['train_items']['cus_name'];
            document.getElementById('insSelect').value=data['train_items']['ins_id'];
            //身体
            // selectDate(data['body_data']['date'],'date','date')
            document.getElementById('date').value=data['body_data']['msr_date'];
            document.getElementById('ht').value = data['body_data']['ht'];
            document.getElementById('wt').value = data['body_data']['wt'];
            document.getElementById('chest').value = data['body_data']['chest'];
            document.getElementById('l_arm').value = data['body_data']['l_arm'];
            document.getElementById('r_arm').value = data['body_data']['r_arm'];
            document.getElementById('waist').value = data['body_data']['waist'];
            document.getElementById('hip').value = data['body_data']['hip'];
            document.getElementById('l_leg').value = data['body_data']['l_leg'];
            document.getElementById('r_leg').value = data['body_data']['r_leg'];
            document.getElementById('l_calf').value = data['body_data']['l_calf'];
            document.getElementById('r_calf').value = data['body_data']['r_calf'];
            document.getElementById('heart').value = data['body_data']['heart'];
            document.getElementById('balance').value = data['body_data']['balance'];
            document.getElementById('power').value = data['body_data']['power'];
            document.getElementById('flex').value = data['body_data']['flex'];
            document.getElementById('core').value = data['body_data']['core'];
            document.getElementById('bodyProblems').value = data['body_data']['body_problems'];

            //训练计划
            document.getElementById('cusGoal').value = data['train_items']['cus_goal'];
            document.getElementById('insSuggest').value = data['train_items']['ins_suggest'];
            document.getElementById('stageSelect').value = data['train_items']['stage'];
            document.getElementById('stageGoal').value = data['train_items']['stage_goal'];
            document.getElementById('trainSummary').value = data['train_items']['train_summary'];
            
            //阶段计划
            const trainStageDetails = data['stage_details']['stage_detail_recs'];

            for (let i = 0; i < trainStageDetails.length; i++) {
                const detailRec = trainStageDetails[i];
                document.getElementById('purposeTxt-'+i).value=detailRec['purpose'];
                document.getElementById('activeTxt-'+i).value=detailRec['active'];
                document.getElementById('benifitTxt-'+i).value=detailRec['benifit'];
                document.getElementById('frqcyTxt-'+i).value=detailRec['frqcy'];
                document.getElementById('partTxt-'+i).value=detailRec['part'];
                document.getElementById('prdTxt-'+i).value=detailRec['prd'];
                document.getElementById('strengthTxt-'+i).value=detailRec['strength'];
                document.getElementById('typeTxt-'+i).value=detailRec['type'];
            }
        }

        function tempSave(show='yes'){
             // 将会员信息保存到本地
            const currentTime=new Date();
            const currentTimeStr=dateToString(currentTime,'dateTime');
            const msrDate=document.getElementById('date').value;
            let ins_id;
            let ins_name;
            if(insRole==='admin'){
                ins_id=document.getElementById('insSelect').value;
                // ins_name=insIdToInsName(ins_id);
            }else if(insRole==='ins'){
                ins_id=insId;
                // ins_name=insIdToInsName(ins_id);
            }else{
                ins_id=insId;
                // ins_name=insIdToInsName(ins_id);
            }


            const bodyData={
                'msr_date':msrDate,
                'ht':document.getElementById('ht').value.trim(),
                'wt':document.getElementById('wt').value.trim(),
                'chest':document.getElementById('chest').value.trim(),
                'l_arm':document.getElementById('l_arm').value.trim(),
                'r_arm':document.getElementById('r_arm').value.trim(),
                'waist':document.getElementById('waist').value.trim(),
                'hip':document.getElementById('hip').value.trim(),
                'l_leg':document.getElementById('l_leg').value.trim(),
                'r_leg':document.getElementById('r_leg').value.trim(),
                'l_calf':document.getElementById('l_calf').value.trim(),
                'r_calf':document.getElementById('r_calf').value.trim(),
                'heart':document.getElementById('heart').value.trim(),
                'balance':document.getElementById('balance').value.trim(),
                'power':document.getElementById('power').value.trim(),
                'flex':document.getElementById('flex').value.trim(),
                'core':document.getElementById('core').value.trim(),
                'body_problems':document.getElementById('bodyProblems').value.trim()
            };

            const trainItems={
                'cus_name':document.getElementById('cusName').value.trim(),
                'cus_goal':document.getElementById('cusGoal').value.trim(),
                'ins_suggest':document.getElementById('insSuggest').value.trim(),
                'stage':document.getElementById('stageSelect').value.trim(),
                'stage_goal':document.getElementById('stageGoal').value.trim(),
                'train_summary':document.getElementById('trainSummary').value.trim(),
                'current_time':currentTimeStr,
                'ins_id':ins_id,
            }

            const stageDetails={
                'cus_name':document.getElementById('cusName').value.trim(),
                'ins_id':ins_id,
                'current_time':currentTimeStr,
                'stage_detail_recs':getTrainDetails()
            }

            const allPlan={
                'body_data':bodyData,
                'train_items':trainItems,
                'stage_details':stageDetails
            }

            // console.log('body_data:',bodyData,'train items:',trainItems,'stage details:',stageDetails);

            const tempSaveCheckRes=tempSaveCheck(allPlan);
            console.log('check res:',tempSaveCheckRes)
            // 检查结果，无问题再保存，并禁用输入框，并显示返回修改按钮。如有，提示，不进行操作。
                 
            if(tempSaveCheckRes==='ok'){       
                
                localStorage.setItem(ins_id+'-'+document.getElementById('cusName').value+'-allPlan',JSON.stringify(allPlan))
                localStorage.setItem(ins_id+'-'+document.getElementById('cusName').value+'-htmlBody',document.documentElement.outerHTML);
                localStorage.setItem(ins_id+'-'+document.getElementById('cusName').value+'-copyCountBody',copyCountBody);
                localStorage.setItem(ins_id+'-'+document.getElementById('cusName').value+'-deleteCountBody',deleteCountBody);
                localStorage.setItem(ins_id+'-'+document.getElementById('cusName').value+'-blockOrderBody',blockOrderBody);
                localStorage.setItem(ins_id+'-'+document.getElementById('cusName').value+'-selectedFileBody','');

                const inputItems = document.querySelectorAll('input');
                inputItems.forEach(function(inputItem){
                    inputItem.disabled=true;
                })

                const textItems = document.querySelectorAll('textarea');
                textItems.forEach(function(textItem){
                    textItem.disabled=true;
                })

                const selectItems = document.querySelectorAll('select');
                selectItems.forEach(function(selectItem){
                    selectItem.disabled=true;
                })

                const deleteButtons=document.querySelectorAll('[id*="deleteTrain-"]')
                deleteButtons.forEach(deleteButton=>{
                    deleteButton.style.display='none';
                })

                try{
                    const deleteTrainButtons=document.querySelectorAll('[id*="deleteTrain-"]');
                    deleteButtons.forEach(deleteButton=>{
                        deleteButton.disabled=true;
                    })
                }
                catch(error){

                }
                

                document.getElementById('copyDetail').disabled=true;
                document.getElementById('upload').disabled=true;
                document.getElementById('browseButton').disabled=true;
                document.getElementById("tempSaveButton").style.display = "none";
                document.getElementById("editButton").style.display = "inline";
                document.getElementById("submit").style.display = "inline";
                document.getElementById("submit").disabled=false;

                if(show==='yes'){
                    alert("体测结果/训练计划已暂存");
                }
            }else{
                document.getElementById("submit").style.display = "none";
                document.getElementById("submit").disabled=true;
                alert(`有些信息未填写或填写错误，请检查: ${tempSaveCheckRes}`);
            }


        }

        function getTrainDetails(){
            const trainDetailDivs=document.querySelectorAll('[id*="trainDetail-"]');


            // let trainDetailAll={}
            let trainDetail=[]
            for(i=0;i<trainDetailDivs.length;i++){
                let trainItem={};
                const id_num=trainDetailDivs[i].id.split('-')[1];  
                
                trainItem['purpose']=document.getElementById('purposeTxt-'+id_num).value;
                trainItem['part']=document.getElementById('partTxt-'+id_num).value;
                trainItem['frqcy']=document.getElementById('frqcyTxt-'+id_num).value;
                trainItem['strength']=document.getElementById('strengthTxt-'+id_num).value;
                trainItem['benifit']=document.getElementById('benifitTxt-'+id_num).value;

                trainItem['type']=document.getElementById('typeTxt-'+id_num).value;
                trainItem['prd']=document.getElementById('prdTxt-'+id_num).value;
                trainItem['active']=document.getElementById('activeTxt-'+id_num).value;
                trainDetail.push(trainItem);
            };
            // trainDetailAll['stage_detail_rec']=trainDetail;

            return trainDetail;
        }

        // 修改数据
        function enableEdit() {
            // 移除禁用属性，并显示保存按钮
            // document.getElementById("nameInput").removeAttribute("disabled");
            const inputItems = document.querySelectorAll('input');
            inputItems.forEach(function(inputItem){
                inputItem.disabled=false;
            })

            const textAreas = document.querySelectorAll('textarea');
            textAreas.forEach(function(textarea){
                textarea.disabled=false;
            })

            const selectItems = document.querySelectorAll('select');
                selectItems.forEach(function(selectItem){
                    selectItem.disabled=false;
                })

            const deleteButtons=document.querySelectorAll('[id*="deleteTrain-"]')
            deleteButtons.forEach(deleteButton=>{
                deleteButton.style.display='block';
            })

    
            const deleteTrainButtons=document.querySelectorAll('[id*="deleteTrain-"]');
            deleteButtons.forEach(deleteButton=>{
                deleteButton.disabled=false;
            })

            document.getElementById('browseButton').disabled=false;
            document.getElementById('upload').disabled=false;
            document.getElementById('copyDetail').disabled=false;            
            document.getElementById("tempSaveButton").style.display = "inline";
            document.getElementById("editButton").style.display = "none";
            document.getElementById("submit").style.display = "none";
        }

        function fillDetailPrompt(id){
            const trainIds=['bodyProblems','cusGoal','insSuggest','trainSummary','stageGoal'];
            const detailIds=['purposeTxt','partTxt','frqcyTxt','strengthTxt','benifitTxt','prdTxt','activeTxt'];
            document.getElementById('bodyProblems').value='1.颈部前引\n2.腰方肌过紧，胸椎活动度偏差\n3.肩峰撞击（肩关节活动度差）';
            document.getElementById('cusGoal').value='1.减脂塑形\n2.体重减至50kg\n3.解决体态问题';
            document.getElementById('insSuggest').value='1.手法松解过紧肌群，消除扳机点\n2.通过康复训练恢复肌肉肌张力平衡\n3.增加活动度和功能训练，避免体态问题复发';
            document.getElementById('trainSummary').value='1.解决了颈部前引的问题\n2.解决了肩峰撞击的问题';
            document.getElementById('stageGoal').value='体态调整、打造体能基础';
            detailIds.forEach(detailId=>{
                if(detailId==='purposeTxt'){
                    document.getElementById(detailId+'-'+id).value='提高心肺、提高肌肉力量';
                }
                if(detailId==='partTxt'){
                    document.getElementById(detailId+'-'+id).value='胸、背、肩、臀腿';
                }
                if(detailId==='frqcyTxt'){
                    document.getElementById(detailId+'-'+id).value='3-4';
                }
                if(detailId==='strengthTxt'){
                    document.getElementById(detailId+'-'+id).value='60-70%';
                }
                if(detailId==='benifitTxt'){
                    document.getElementById(detailId+'-'+id).value='肌肉含量提高、代谢提高';
                }    
                if(detailId==='prdTxt'){
                    document.getElementById(detailId+'-'+id).value='50';
                }
                if(detailId==='activeTxt'){
                    document.getElementById(detailId+'-'+id).value='5-10';
                }
            });

         
        }

        function copyDetail(){
            copyCountBody+=1;
            blockOrderBody+=1;
            const originalDiv=document.getElementById('trainDetail-0');
            const copiedDiv=originalDiv.cloneNode(true);
            traverseElementsRename(copiedDiv,(blockOrderBody-1));
            copiedDiv.id='trainDetail-'+(blockOrderBody-1);
            copiedDiv.querySelector('#trainRecCount-'+(blockOrderBody-1)).textContent='阶段训练计划分解 第'+(blockOrderBody)+'条';

            // 增加删除按钮
            const deleteTrain=document.createElement('button');
            deleteTrain.setAttribute('id','deleteTrain-'+(blockOrderBody-1)); 
            deleteTrain.textContent='删除';
            deleteTrain.addEventListener('click',function(){
                deleteTrainBlock(this,parent='y');
            })

            // 从第3条开始，删除上一个输入块的删除按钮
            if(blockOrderBody>=3){
                const deleteTrainPrevious=document.getElementById('deleteTrain-'+(blockOrderBody-2));
                deleteTrainPrevious.remove();
            }

            // 调整原来的分隔线到删除按钮下
            const hrElement=copiedDiv.querySelector('hr');
            hrElement.remove();
            copiedDiv.appendChild(deleteTrain);
            const hr=document.createElement('hr');
            copiedDiv.appendChild(hr);

            // 新的copiedDiv加到下面
            originalDiv.parentNode.appendChild(copiedDiv);

            // 将值初始化
            document.getElementById('typeTxt'+'-'+(blockOrderBody-1)).selectedIndex=0;
            // document.getElementById('purposeTxt-'+(blockOrderBody-1)).value='';
            // document.getElementById('partTxt-'+(blockOrderBody-1)).value='';
            // document.getElementById('frqcyTxt-'+(blockOrderBody-1)).value='';
            // document.getElementById('strengthTxt-'+(blockOrderBody-1)).value='';
            // document.getElementById('benifitTxt-'+(blockOrderBody-1)).value='';
            // document.getElementById('prdTxt-'+(blockOrderBody-1)).value='';
            // document.getElementById('activeTxt-'+(blockOrderBody-1)).value='';
            fillDetailPrompt(blockOrderBody-1)


        }

        function deleteTrainBlock(blk,parent){
            let deleteBlock;
            deleteCountBody+=1;
            blockOrderBody=blockOrderBody-1;
            if(parent==='y'){
                deleteBlock=blk.parentNode;
            }else{
                deleteBlock=blk;
            }
            
            // const previousTrainBlock=buttonDeleteTrain.previousElementSibling;
            const previousTrainBlock=document.getElementById('trainDetail-'+(parseInt(blk.id.slice(-1))-1))
            

            if(blockOrderBody>=2){
                
                const deleteTrain=document.createElement('button');
                deleteTrain.setAttribute('id','deleteTrain-'+(blockOrderBody-1)); 
                deleteTrain.textContent='删除';
                deleteTrain.addEventListener('click',function(){
                    deleteTrainBlock(previousTrainBlock,'n');
                });
                const hrElement=previousTrainBlock.querySelector('hr');
                hrElement.remove();
                previousTrainBlock.appendChild(deleteTrain);
                const hr=document.createElement('hr');
                previousTrainBlock.appendChild(hr);
            }

            deleteBlock.remove();
            
            
        }

        function insIdToInsName(insId){
            let insNameFromId;
            let ctn=true;
            // console.log(ins_list)
            ins_list.forEach(function(insItem){
                if(ctn){
                    if(insItem.includes(insId)){
                    insNameFromId=insItem.slice(8,);
                    ctn=false;
                    }
                }                
            })
            return insNameFromId;
        }

        function traverseElementsRename(element,num) {
        // 遍历当前元素的子节点
            for (let child of element.children) {
   
                ptn=/.*-\d{0,1}/;        
                if(ptn.test(child.id)){
                    child.id=child.id.slice(0,-1)+num;
                    
                }
                if(ptn.test(child.name)){
                    child.name=child.name.slice(0,-1)+num;
                }

                const labelFor=child.getAttribute('for');
                if(ptn.test(labelFor)){
                    child.htmlFor=child.htmlFor.slice(0,-1)+num;
                }
                // console.log('new',child.id);

                // 如果当前元素有子元素，则递归调用 traverseElements 函数
                if (child.children.length > 0) {
                    traverseElementsRename(child,num);
                }
                }
        }

        function hideProcessingModel() {
            document.getElementById('processingModel').style.display = 'none';
        }

        function showProcessingModel() {
            document.getElementById('processingModel').style.display = 'block';
        }

        function submitCheck(allPlan){
            const inputs=document.querySelectorAll('input');
            const textareas = document.querySelectorAll('textarea');
            // console.log(inputs);

            const idNameDic={
                'cusName':'会员姓名',
                'ht':'身高',
                'wt':'体重',
                'chest':'胸围',
                'l_arm':'左臂围',
                'r_arm':'右臂围',
                'waist':'腰围',
                'hip':'臀围',
                'l_leg':'左大腿围',
                'r_leg':'右大腿围',
                'l_calf':'左小腿围',
                'r_calf':'右小腿围',
                'heart':'心肺',
                'balance':'平衡',
                'power':'力量',
                'flex':'柔韧性',
                'core':'核心',
                'bodyProblems':'体测发现问题',
                'cusGoal':'会员健身需求',
                'insSuggest':'教练针对性建议',
                'stageGoal':'阶段目标',
                'purposeTxt':'训练目标',
                'partTxt':'部位分化',
                'frqcyTxt':'训练频率',
                'strengthTxt':'训练强度',
                'benifitTxt':'预期训练收益',
                'typeTxt':'训练类型',
                'prdTxt':'训练用时',
                'activeTxt':'激活拉伸时间',
                'trainSummary':'训练回顾'
            };

            let blank=0;
            let num=1;
            let checkValueEmpty=0;
            let emptyItem='';
            try{               

                inputs.forEach(input=>{
                    if(!['fileInput','_w_simile'].includes(input.id) && input.value.trim()===''){                          
                        // console.log('数据检查：填写数据有空项');       
                        if(input.id.includes('-')){
                            emptyItem=emptyItem+','+`第${parseInt(input.id.split('-')[1])+1}条阶段计划“ ${idNameDic[input.id.split('-')[0]]}”`   
                        }else{
                            emptyItem=emptyItem+','+`${idNameDic[input.id]}`   
                        }
                         
                        blank+=1;
                    }
                });

                textareas.forEach(textarea=>{
                    if(textarea.value.trim()==='' && textarea.id!=='trainSummary'){                          
                        // console.log('数据检查：填写数据有空项');       
                        if(textarea.id.includes('-')){
                            emptyItem=emptyItem+','+`第${parseInt(textarea.id.split('-')[1])+1}条阶段计划“ ${idNameDic[textarea.id.split('-')[0]]}”`   
                        }else{
                            emptyItem=emptyItem+','+`${idNameDic[textarea.id]}`   
                        }
                         
                        blank+=1;
                    }
                });
            

                if(blank>0){                    
                    throw new Error('以下内容有空项：'+emptyItem.slice(1,));
                }

                if(parseFloat(document.getElementById('ht').value)<0){
                    throw new Error('身高为负数');
                }
                if(parseFloat(document.getElementById('wt').value)<0){
                    throw new Error('体重为负数');
                }
                if(parseFloat(document.getElementById('chest').value)<0){
                    throw new Error('胸围为负数');
                }
                if(parseFloat(document.getElementById('l_arm').value)<0){
                    throw new Error('左臂围为负数');
                }
                if(parseFloat(document.getElementById('r_arm').value)<0){
                    throw new Error('右臂围为负数');
                }
                if(parseFloat(document.getElementById('waist').value)<0){
                    throw new Error('腰围为负数');
                }
                if(parseFloat(document.getElementById('hip').value)<0){
                    throw new Error('臀围为负数');
                }

                if(parseFloat(document.getElementById('l_leg').value)<0){
                    throw new Error('左大腿围为负数');
                }

                if(parseFloat(document.getElementById('r_leg').value)<0){
                    throw new Error('右大腿围为负数');
                }

                if(parseFloat(document.getElementById('l_calf').value)<0){
                    throw new Error('左小腿围为负数');
                }
                if(parseFloat(document.getElementById('r_calf').value)<0){
                    throw new Error('右小腿围为负数');
                }
                if(parseFloat(document.getElementById('heart').value)<0){
                    throw new Error('心肺为负数');
                }
                if(parseFloat(document.getElementById('balance').value)<0){
                    throw new Error('平衡为负数');
                }
                if(parseFloat(document.getElementById('power').value)<0){
                    throw new Error('力量为负数');
                }
                if(parseFloat(document.getElementById('flex').value)<0){
                    throw new Error('柔韧性为负数');
                }
                if(parseFloat(document.getElementById('core').value)<0){
                    throw new Error('核心为负数');
                }
                if(parseFloat(document.getElementById('heart').value)>10){
                    throw new Error('心肺超范围');
                }
                if(parseFloat(document.getElementById('balance').value)>10){
                    throw new Error('平衡超范围');
                }
                if(parseFloat(document.getElementById('power').value)>10){
                    throw new Error('力量超范围');
                }
                if(parseFloat(document.getElementById('flex').value)>10){
                    throw new Error('柔韧性超范围');
                }
                if(parseFloat(document.getElementById('core').value)>10){
                    throw new Error('核心超范围');
                }
            
            return 'ok';

        }catch(error){
            return error;
        }
            
            
        }

        function tempSaveCheck(allPlan){
            const inputs=document.querySelectorAll('input');
            const textareas = document.querySelectorAll('textarea');
            // console.log(inputs);

            const checkId=['cusName','ht','wt','chest','l_arm',
                'r_arm',
                'waist',
                'hip',
                'l_leg',
                'r_leg',
                'l_calf',
                'r_calf',
                'heart',
                'balance',
                'power',
                'flex',
                'core']

            const idNameDic={
                'cusName':'会员姓名',
                'ht':'身高',
                'wt':'体重',
                'chest':'胸围',
                'l_arm':'左臂围',
                'r_arm':'右臂围',
                'waist':'腰围',
                'hip':'臀围',
                'l_leg':'左大腿围',
                'r_leg':'右大腿围',
                'l_calf':'左小腿围',
                'r_calf':'右小腿围',
                'heart':'心肺',
                'balance':'平衡',
                'power':'力量',
                'flex':'柔韧性',
                'core':'核心',
                'bodyProblems':'体测发现问题',
                'cusGoal':'会员健身需求',
                'insSuggest':'教练针对性建议',
                'stageGoal':'阶段目标',
                'purposeTxt':'训练目标',
                'partTxt':'部位分化',
                'frqcyTxt':'训练频率',
                'strengthTxt':'训练强度',
                'benifitTxt':'预期训练收益',
                'typeTxt':'训练类型',
                'prdTxt':'训练用时',
                'activeTxt':'激活拉伸时间',
                'trainSummary':'训练回顾'
            };

            let blank=0;
            let num=1;
            let checkValueEmpty=0;
            let emptyItem='';
            try{               

                inputs.forEach(input=>{
                    if(checkId.includes(input.id) && input.id!=='_w_simile' && input.value.trim()===''){                          
                        // console.log('数据检查：填写数据有空项');       
                        if(input.id.includes('-')){
                            emptyItem=emptyItem+','+`第${parseInt(input.id.split('-')[1])+1}条阶段计划“ ${idNameDic[input.id.split('-')[0]]}”`   
                        }else{
                            emptyItem=emptyItem+','+`${idNameDic[input.id]}`   
                        }
                         
                        blank+=1;
                    }
                });

                textareas.forEach(textarea=>{
                    if(checkId.includes(textarea.id) && textarea.value.trim()==='' && textarea.id!=='trainSummary'){                          
                        // console.log('数据检查：填写数据有空项');       
                        if(textarea.id.includes('-')){
                            emptyItem=emptyItem+','+`第${parseInt(textarea.id.split('-')[1])+1}条阶段计划“ ${idNameDic[textarea.id.split('-')[0]]}”`   
                        }else{
                            emptyItem=emptyItem+','+`${idNameDic[textarea.id]}`   
                        }
                         
                        blank+=1;
                    }
                });
            

                if(blank>0){                    
                    throw new Error('以下内容有空项：'+emptyItem.slice(1,));
                }

                if(parseFloat(document.getElementById('ht').value)<0){
                    throw new Error('身高为负数');
                }
                if(parseFloat(document.getElementById('wt').value)<0){
                    throw new Error('体重为负数');
                }
                if(parseFloat(document.getElementById('chest').value)<0){
                    throw new Error('胸围为负数');
                }
                if(parseFloat(document.getElementById('l_arm').value)<0){
                    throw new Error('左臂围为负数');
                }
                if(parseFloat(document.getElementById('r_arm').value)<0){
                    throw new Error('右臂围为负数');
                }
                if(parseFloat(document.getElementById('waist').value)<0){
                    throw new Error('腰围为负数');
                }
                if(parseFloat(document.getElementById('hip').value)<0){
                    throw new Error('臀围为负数');
                }

                if(parseFloat(document.getElementById('l_leg').value)<0){
                    throw new Error('左大腿围为负数');
                }

                if(parseFloat(document.getElementById('r_leg').value)<0){
                    throw new Error('右大腿围为负数');
                }

                if(parseFloat(document.getElementById('l_calf').value)<0){
                    throw new Error('左小腿围为负数');
                }
                if(parseFloat(document.getElementById('r_calf').value)<0){
                    throw new Error('右小腿围为负数');
                }
                if(parseFloat(document.getElementById('heart').value)<0){
                    throw new Error('心肺为负数');
                }
                if(parseFloat(document.getElementById('balance').value)<0){
                    throw new Error('平衡为负数');
                }
                if(parseFloat(document.getElementById('power').value)<0){
                    throw new Error('力量为负数');
                }
                if(parseFloat(document.getElementById('flex').value)<0){
                    throw new Error('柔韧性为负数');
                }
                if(parseFloat(document.getElementById('core').value)<0){
                    throw new Error('核心为负数');
                }
                if(parseFloat(document.getElementById('heart').value)>10){
                    throw new Error('心肺超范围');
                }
                if(parseFloat(document.getElementById('balance').value)>10){
                    throw new Error('平衡超范围');
                }
                if(parseFloat(document.getElementById('power').value)>10){
                    throw new Error('力量超范围');
                }
                if(parseFloat(document.getElementById('flex').value)>10){
                    throw new Error('柔韧性超范围');
                }
                if(parseFloat(document.getElementById('core').value)>10){
                    throw new Error('核心超范围');
                }
            
            return 'ok';

        }catch(error){
            return error;
        }
            
            
        }



        function submit(){
            const checkResult=submitCheck();
            if(checkResult==='ok'){
                console.log('数据完整');                

                const stageIds=['stageSelect','stageGoal','purposeTxt','partTxt','frqcyTxt','strengthTxt','benifitTxt','typeTxt','prdTxt','activeTxt']
                
                let dicBody={};
                
                dicBody['stage']={};
                dicBody['stage']['detailRecs']={};
                const inputs=document.querySelectorAll('input');
                inputs.forEach(input=>{
                    if(input.id!=='_w_simile'){
                        if(stageIds.includes(input.id.split('-')[0])){
                            if(input.id.includes('-')){
                                dicBody['stage']['detailRecs'][input.id]=input.value;
                                
                            }else{
                                dicBody['stage'][input.id]=input.value;
                            }
                        }else{
                            dicBody[input.id]=input.value;
                        }
                        
                    }
                });

                const textAreas=document.querySelectorAll('textarea');
                textAreas.forEach(textarea=>{                     
                    if(stageIds.includes(textarea.id.split('-')[0])){
                            if(textarea.id.includes('-')){
                                dicBody['stage']['detailRecs'][textarea.id]=textarea.value;
                                
                            }else{
                                dicBody['stage'][textarea.id]=textarea.value;
                            }
                        }else{
                            dicBody[textarea.id]=textarea.value;
                        }               
                });

                const selects=document.querySelectorAll('select');
                selects.forEach(selectItem=>{                    
                    // dicBody[selectItem.id]=selectItem.value;   
                    if(stageIds.includes(selectItem.id.split('-')[0])){
                            if(selectItem.id.includes('-')){
                                dicBody['stage']['detailRecs'][selectItem.id]=selectItem.value;
                                
                            }else{
                                dicBody['stage'][selectItem.id]=selectItem.value;
                            }
                    }else{                        
                        dicBody[selectItem.id]=selectItem.value;
                    }                      
                });
                //根据角色重写insSelect及
                let insIdPage;
                if(insRole==='ins'){
                    insIdPage=insId;
                }else if(insRole==='admin'){
                    insIdPage=document.getElementById('insSelect').value;
                }else{
                    insIdPage=insId;
                }
                dicBody['insSelect']=insIdPage;

                // 处理日期的格式
                dicBody['date']=dateFormat(new Date(document.getElementById('date').value),'date');
                dicBody['body_problems']=document.getElementById('bodyProblems').value.trim();
                dicBody['opr_id']=insId;
                dicBody['opr_time']=currentLocalTime();
                if(selectedFile){
                    dicBody['comp_pic_name']=newSelectedName(selectedFile.name);
                }else{
                    dicBody['comp_pic_name']=null;
                }
                

                // console.log('dicBody:',dicBody);
                showProcessingModel();
                fetch('./write_body',{
                    method:"POST",
                    headers:{
                        'Content-Type':'application/json'
                    },
                    body: JSON.stringify(dicBody)
                })
                .then(response=>response.json())
                .then(data=>{
                    hideProcessingModel();
                    // console.log(data['res']);

                    if(data['res']==='ok'){
                        removeLocalStorage(insIdPage,dicBody['cusName'])
                        alert('已录入体测及训练计划');
                        window.location.replace('./');
                    }else{
                        if(data['error'].includes('Duplicate entry')){
                            alert('该会员同一天已有体测记录及计划，如确认无误，请联系管理员增加记录。');
                        }else{
                            alert('身体数据/训练计划录入错误，请联系管理员。');
                        }
                        
                        window.location.replace('./');
                    }
                    
                })
                .catch(error=>{
                    console.error('身体数据/训练计划写入错误：',error)
                });

            }else{
                alert(checkResult);   
                console.log('填写数据有空项');
            }
            
        }

        
        function removeLocalStorage(insId,cusIdName){
            
            Object.keys(localStorage).forEach(key=>{
                
                if(key.split('-')[0]===insId && key.split('-')[1]===cusIdName){
                    console.log(key)
                    localStorage.removeItem(key);
                }
            });
        }

        function showHistory(data){
            // console.log('body msr history:',data);
            const bodyHistory=document.getElementById('bodyHistory');
            bodyHistory.innerHTML='';
            const bodyHistoryCountContent=document.createElement('div');
            if(data[0]['日期']===''){
                bodyHistoryCountContent.innerHTML=`<div id="bodyHistoryCount" style="padding:10px;font-size:16px;"><b> · 没有过去体测的数据</b></div>`;
                bodyHistory.appendChild(bodyHistoryCountContent);
            }else{
                bodyHistoryCountContent.innerHTML=`<div id="bodyHistoryCount" style="padding:10px;font-size:16px;"><b> · 过去一共体测 ${Object.keys(data).length} 次</b></div>`;    
                bodyHistory.appendChild(bodyHistoryCountContent);
                for(i=0;i<Object.keys(data).length;i++){
                    const bodyProblemTxt=data[i]['体测问题']?data[i]['体测问题']:'-';
                    const newDiv=document.createElement('div')
                    newDiv.id=`history-${i}`;
                    newDiv.innerHTML=`                    
                    <div style="vertical-align:bottom;background-color:#ffffff" ><span style="background-color:#7f1f97;padding-left:10px;padding-right:10px;padding-top:3px;padding-bottom:3px;border-radius:2px;color:#ffffff;font-size:8px;">第 ${(i+1)} 条</span><b><span>   体测日期</span><span style="width:25px;"></span> ${dateFormat(new Date(data[i]['日期']),'date')}</b></div> 
                        <hr>
                        <table>
                            <tr>
                            <td ><span>身高 </span>${data[i]['身高（cm）']} cm</td>
                            <td style="padding-left:15px;"><span>体重 </span>${data[i]['体重（Kg）']} Kg</td>
                            </tr>
                            <tr>
                            <td><span>估算体脂率 </span>${(parseFloat(data[i]['体脂率'])*100).toFixed(2)} %</td>
                            </tr>
                            <tr>
                            <td ><span>胸围 </span>${data[i]['胸围']} cm</td>
                            <td style="padding-left:15px;"><span>腰围 </span>${data[i]['腰围']} cm</td>
                            </tr>
                            <tr>
                            <td><span>臀围 </span>${data[i]['臀围']} cm</td>
                            </tr>
                            <tr>
                            <td><span>左臂围 </span>${data[i]['左臂围']} cm</td>
                            <td style="padding-left:15px;"><span>右臂围 </span>${data[i]['右臂围']} cm</td>
                            </tr>
                            <tr>
                            <td><span>左大腿围 </span>${data[i]['左腿围']} cm</td>
                            <td style="padding-left:15px;"><span>右大腿围： </span>${data[i]['右腿围']} cm</td>
                            </tr>
                            <tr>
                            <td><span>左小腿围 </span>${data[i]['左小腿围']} cm</td>
                            <td style="padding-left:15px;"><span>右小腿围 </span>${data[i]['右小腿围']} cm</td>
                            </tr>
                            
                        </table>
                        <div style='margin-left:6px;'><span style='color:#cf3256;'>体测问题： </span>${bodyProblemTxt}</div>
                        `;
                    
                    
                    bodyHistory.appendChild(newDiv);
                }
                //大于1条的折叠，最留最近一条记录
                for(i=0;i<Object.keys(data).length;i++){
                    if(i!==Object.keys(data).length-1){
                        const  historyBlock=document.getElementById(`history-${i}`);
                        historyBlock.style.display='none';
                    }                    
                }
                
                if(Object.keys(data).length>1){
                    const firstDiv=document.getElementById('history-0');
                    const hideButton=document.createElement('button')
                    hideButton.textContent='显示全部体测记录';
                    hideButton.addEventListener('click',function(){
                        if( hideButton.textContent==='显示全部体测记录'){
                            hideButton.textContent='只显示最近一条记录';
                        }else{
                            hideButton.textContent='显示全部体测记录';
                        }
                       
                        for(i=0;i<Object.keys(data).length-1;i++){
                            const  historyBlock=document.getElementById(`history-${i}`);
                           
                            if(window.getComputedStyle(historyBlock).getPropertyValue('display')=='none'){
                                historyBlock.style.display='inline';
                            }else{
                                historyBlock.style.display='none';
                            }
                        }
                            
                    })
                    bodyHistory.insertBefore(hideButton,firstDiv);
                }
            }
        }
        
        function getBodyHistory(){
            const bodyProblems=document.getElementById('bodyProblems');
            const bodyProblemsTitle=document.getElementById('bodyProblemsTitle');
            const cusName=document.getElementById('cusName').value;
            fetch('/get_body_history',{
                method:"POST",
                headers:{
                    'Content-Type':"text/plain"
                },
                body:cusName
            })
            .then(response=>response.json())
            .then(data=>{
                // console.log('get body history():',data);
                showHistory(data);
                //如果没有既往体测历史，读取体验课发现问题的记录
                if(data[0]['日期']===''){                    
                    getTrialProblem(cusName);
                }else{
                    bodyProblemsTitle.textContent='体测发现问题';
                    bodyProblems.value='1.颈部前引\n2.腰方肌过紧，胸椎活动度偏差\n3.肩峰撞击（肩关节活动度差）';
                }


            })
            .catch(error=>{
                console.error('Error:',error)
            });
        }
        
       
        function handleInput() {
            // 获取输入框中的值
            const searchTerm = document.getElementById("cusName").value.trim();
            const UpperSearchTerm=searchTerm.toUpperCase();
            // 获取展示结果的列表元素
            const resultList = document.getElementById("cusList");

            // 清空列表
            resultList.innerHTML = "";

            if (UpperSearchTerm === "") {
                resultList.style.display = "none";
                return; // 输入框为空，不做处理
            }else{
                resultList.style.display = "block";

            }

            // 遍历给定的数组，进行模糊匹配
            cus_list.reverse().forEach(function(name) {
                if (name.includes(UpperSearchTerm)) {
                    // 创建列表项元素，并设置其文本内容为匹配到的结果
                    const listItem = document.createElement("li");
                    listItem.innerText = name;

                    // 添加点击事件监听器
                    listItem.addEventListener("click", function() {
                        // 点击后将完整的姓名设置为输入框的值
                        document.getElementById("cusName").value = name;
                        document.getElementById("browseButton").disabled = false;
                        document.getElementById("upload").disabled = false;
                        document.getElementById("tempSaveButton").disabled = false;
                        document.getElementById('uploadMsg').textContent='';
                        

                        resultList.style.display = "none";
                        // const bodyHistory=getBodyHistory();
                        getBodyHistory();
                       
                        // 手动触发change事件
                        // nameInput.dispatchEvent(new Event('change'));
                        // 清空结果列表
                        let insIdPage;
                        if(insRole==='admin'){
                            insIdPage=document.getElementById('insSelect').value;
                        }else{
                            insIdPage=insId;
                        }

                        // console.log('local storage:',insIdPage+'-'+name+'-htmlBody')
                        const tempSavePage=localStorage.getItem(insIdPage+'-'+name+'-htmlBody');
                        if(tempSavePage){
                            const isConfirmed=confirm('该会员有一条暂存信息，是否需要读取？');
                            if(isConfirmed){
                                const allPlanContents=document.getElementById('allPlanContents');
                                // allPlanContents.style.display='block';
                                reloadPage(tempSavePage,name);
                            }                          
                        }

                        checkTrainSummaryShow();

                        resultList.innerHTML = "";
                    });

                    // 将列表项添加到结果列表中
                    resultList.appendChild(listItem);

                    
                }else{
                    const bodyHistory=document.getElementById('bodyHistory');
                    bodyHistory.innerHTML='';
                    document.getElementById("browseButton").disabled = true;
                    document.getElementById("upload").disabled = true;
                    document.getElementById("tempSaveButton").disabled = true;
                    document.getElementById('uploadMsg').textContent='';
                }
            });
        
            // resultList.classList.add("cus-list");
            
        }

        function getTrialProblem(cusIdName){       
            const bodyProblemsTitle=document.getElementById('bodyProblemsTitle');  
            const bodyProblems=document.getElementById('bodyProblems');
            fetch('/get_trial_problem',{
            method:"POST",
            headers:{
                "Content-Type":"application/json"
            },
            body: JSON.stringify({'cusIdName':cusIdName})
            })
            .then(response=>response.json())
            .then(data=>{    
                if(data['res']==='ok'){
                    // console.log('trial problem:',data['data'])
                    bodyProblemsTitle.textContent='体测发现问题（体验课体测问题记录如下）';
                    bodyProblems.value=data['data'][0];
                }else{
                    bodyProblemsTitle.textContent='体测发现问题';
                    bodyProblems.value='1.颈部前引\n2.腰方肌过紧，胸椎活动度偏差\n3.肩峰撞击（肩关节活动度差）';
                    console.log(data['error']);
                    
                }

            })
            .catch(error=>{
                console.log(error)
            });
            
        }

        function reloadPage(tempSavePage,name){
            let insIdPage;
            if(insRole==='admin'){
                insIdPage=document.getElementById('insSelect').value;
            }else{
                insIdPage=insId;
            }
            // window.selectedFile = "ddd";
            document.documentElement.innerHTML=tempSavePage;

            //重置浏览按钮
            reSetupFileSelection();

            // console.log(insName+'-'+name+'-cls_recs');
            reFillTempSave(localStorage.getItem(insIdPage+'-'+name+'-allPlan'));

            // tempSave('no');
        }

        function reSetupFileSelection(){
            const fileInput = document.getElementById('fileInput'); // 获取文件上传的 input 元素
            fileInput.addEventListener('change', handleFileSelection);
            document.getElementById('uploadMsg').textContent='';
        }

        function reSetupDateSelect(){
            const date = document.getElementById('date'); // 获取文件上传的 input 元素
            date.addEventListener('change', checkTrainSummaryShow);

        }

        function openFileBrowser() {
            document.getElementById('fileInput').click();
        }

        function newSelectedName(name){
            let insIdPage;
            if(insRole==='admin'){
                insIdPage=document.getElementById('insSelect').value;
            }else if(insRole==='ins'){
                insIdPage=insId;
            }else{
                insIdPage=insId;
            }
            const cusName=document.getElementById('cusName').value;
            const dateSelect=dateToString(document.getElementById('date').value,'digit8');
            const fileExtension = name.split('.').pop();
            const filename = insIdPage + '-' + cusName + '-' + dateSelect + '.' + fileExtension;
            return filename
        }

        function handleFileSelection(event) {
            selectedFile = event.target.files[0];
            const uploadMsg=document.getElementById('uploadMsg');
            const newFileName=newSelectedName(selectedFile.name);
            uploadMsg.textContent=`已选择文件：${newFileName}`
           
        }

        function uploadFile() {
            if (!selectedFile) {
                alert("请选择要上传的图片");
                return;
            }

            const newFileName=newSelectedName(selectedFile.name);
            
            const url = "/upload_pic?filename=" + encodeURIComponent(newFileName);

            let formData = new FormData();
            formData.append("file", selectedFile); 
            formData.append("filename", newFileName);
            // console.log(url)

            let xhr = new XMLHttpRequest();
            xhr.open("POST", url);
            xhr.onload = function() {
                console.log('xhr status:',xhr.status)
                const errorResponse = JSON.parse(xhr.responseText);
                const errorMessage = errorResponse.message;
                // console.log('message:',errorMessage)
                if (xhr.status === 200) {
                    document.getElementById('uploadMsg').textContent=`${newFileName} 上传成功`;
                    // alert("上传成功");
                } else {
                    document.getElementById('uploadMsg').textContent='上传失败，请联系管理员。'
                    alert("上传失败，请联系管理员。错误："+errorMessage);
                }
            };
            xhr.send(formData);
        }
    </script>
</body>